package com.dingyuhang.aop;

import com.alibaba.fastjson.JSON;
import com.dingyuhang.bean.TbLog;
import com.dingyuhang.service.TbLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
public class MyLog {
    @Autowired
    TbLogService tbLogService;


    //环绕通知 --使用自定义注解
  //  @Around(value = "@annotation(com.dingyuhang.util.MyAnn)")
//   @Around("@annotation(MyAnn)")
    public  Object log1(ProceedingJoinPoint pjp ) throws Throwable {

   //        //记录请求的日志


        ServletRequestAttributes requestAttributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //1获取请求的类的url
        String requestURI = requestAttributes.getRequest().getRequestURI();

     //   String method = pjp.getSignature().getName();//1获取请求的类的方法名
        Object[] args = pjp.getArgs();
        String params = JSON.toJSONString(args);//2请求参数
        //封装对象
        TbLog tbLog = new TbLog(requestURI, params, new Date());
        tbLogService.addLog(tbLog);
        Object proceed = pjp.proceed();//调用目标方法
        return proceed;
    }
}
